<template>
  <view class="category-detail">
    <!-- 导航栏 -->
    <NavBar :title="categoryName" />

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view 
        class="filter-item" 
        :class="{ active: sortType === 'default' }"
        @click="changeSort('default')"
      >
        默认
      </view>
      <view 
        class="filter-item" 
        :class="{ active: sortType === 'sales' }"
        @click="changeSort('sales')"
      >
        销量
      </view>
      <view 
        class="filter-item price-sort" 
        :class="{ active: sortType === 'price-asc' || sortType === 'price-desc' }"
        @click="togglePriceSort"
      >
        价格
        <view class="sort-icon">
          <ArrowUp size="12" :color="sortType === 'price-asc' ? '#fa2c19' : '#999'" />
          <ArrowDown size="12" :color="sortType === 'price-desc' ? '#fa2c19' : '#999'" />
        </view>
      </view>
      <view 
        class="filter-item" 
        :class="{ active: showFilterPanel }"
        @click="toggleFilterPanel"
      >
        筛选
        <Filter size="14" />
      </view>
    </view>

    <!-- 筛选面板 -->
    <nut-popup position="right" v-model:visible="showFilterPanel" :style="{ width: '80%', height: '100%' }">
      <view class="filter-panel">
        <view class="panel-header">
          <text class="title">筛选条件</text>
          <Close @click="showFilterPanel = false" />
        </view>
        
        <view class="panel-content">
          <!-- 价格区间 -->
          <view class="filter-section">
            <view class="section-title">价格区间</view>
            <view class="price-range">
              <nut-input-number v-model="minPrice" placeholder="最低价" />
              <text class="separator">-</text>
              <nut-input-number v-model="maxPrice" placeholder="最高价" />
            </view>
          </view>
          
          <!-- 品牌筛选 -->
          <view class="filter-section">
            <view class="section-title">品牌</view>
            <view class="brand-list">
              <nut-checkbox-group v-model="selectedBrands">
                <nut-checkbox 
                  v-for="(brand, index) in brands" 
                  :key="index"
                  :label="brand.id"
                >
                  {{ brand.name }}
                </nut-checkbox>
              </nut-checkbox-group>
            </view>
          </view>
          
          <!-- 其他筛选条件 -->
          <view class="filter-section">
            <view class="section-title">其他</view>
            <view class="other-filters">
              <nut-checkbox-group v-model="otherFilters">
                <nut-checkbox label="hasDiscount">优惠商品</nut-checkbox>
                <nut-checkbox label="hasStock">有库存</nut-checkbox>
                <nut-checkbox label="isFreeShipping">包邮</nut-checkbox>
              </nut-checkbox-group>
            </view>
          </view>
        </view>
        
        <view class="panel-footer">
          <nut-button @click="resetFilter">重置</nut-button>
          <nut-button type="primary" @click="applyFilter">确定</nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- 商品列表 -->
    <view class="goods-list">
      <!-- 空结果提示 -->
      <nut-empty v-if="goodsList.length === 0" description="暂无相关商品" image="search" />

      <!-- 商品列表 -->
      <nut-grid v-else :column-num="2" :border="false">
        <nut-grid-item
          v-for="(item, index) in goodsList"
          :key="index"
          @click="onGoodsClick(item)"
        >
          <view class="goods-card">
            <image :src="item.imgUrl" style="width: 100%; height: 150px; border-radius: 4px;" />
            <view class="goods-info">
              <view class="goods-name">{{ item.name }}</view>
              <view class="price-info">
                <nut-price :price="item.price" size="normal" />
                <nut-price v-if="item.vipPrice" :price="item.vipPrice" size="small" class="vip-price" />
              </view>
              <view class="goods-tags">
                <nut-tag type="primary" plain size="small" v-if="item.isFreeShipping">包邮</nut-tag>
                <nut-tag type="danger" plain size="small" v-if="item.hasDiscount">优惠</nut-tag>
              </view>
            </view>
          </view>
        </nut-grid-item>
      </nut-grid>

      <!-- 加载更多 -->
      <view v-if="goodsList.length > 0" class="load-more">
        <view v-if="hasMore" class="loading" @click="loadMore">
          <Loading size="16px" /> 加载中...
        </view>
        <view v-else class="no-more">没有更多了</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { ArrowUp, ArrowDown, Filter, Close, Loading } from '@nutui/icons-vue-taro'
import NavBar from '@/components/NavBar/index.vue'

// 获取路由参数
const router = Taro.getCurrentInstance().router
const categoryId = router?.params?.id || ''
const categoryName = router?.params?.name || '分类详情'

// 排序相关
const sortType = ref('default')
const showFilterPanel = ref(false)

// 筛选条件
const minPrice = ref('')
const maxPrice = ref('')
const selectedBrands = ref([])
const otherFilters = ref([])

// 品牌列表
const brands = ref([
  { id: '1', name: '苹果' },
  { id: '2', name: '华为' },
  { id: '3', name: '小米' },
  { id: '4', name: 'OPPO' },
  { id: '5', name: 'vivo' },
  { id: '6', name: '三星' }
])

// 商品列表
const goodsList = ref([])
const currentPage = ref(1)
const hasMore = ref(true)
const loading = ref(false)

// 切换排序方式
const changeSort = (type) => {
  sortType.value = type
  resetList()
}

// 切换价格排序
const togglePriceSort = () => {
  if (sortType.value === 'price-asc') {
    sortType.value = 'price-desc'
  } else {
    sortType.value = 'price-asc'
  }
  resetList()
}

// 切换筛选面板
const toggleFilterPanel = () => {
  showFilterPanel.value = !showFilterPanel.value
}

// 重置筛选条件
const resetFilter = () => {
  minPrice.value = ''
  maxPrice.value = ''
  selectedBrands.value = []
  otherFilters.value = []
}

// 应用筛选条件
const applyFilter = () => {
  showFilterPanel.value = false
  resetList()
}

// 重置列表
const resetList = () => {
  currentPage.value = 1
  hasMore.value = true
  getGoodsList()
}

// 获取商品列表
const getGoodsList = async () => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    // 构建查询参数
    const params = {
      categoryId,
      page: currentPage.value,
      pageSize: 10,
      sortType: sortType.value,
      minPrice: minPrice.value,
      maxPrice: maxPrice.value,
      brands: selectedBrands.value.join(','),
      hasDiscount: otherFilters.value.includes('hasDiscount'),
      hasStock: otherFilters.value.includes('hasStock'),
      isFreeShipping: otherFilters.value.includes('isFreeShipping')
    }
    
    // 实际项目中应该调用API获取商品列表
    // const res = await api.goods.getGoodsList(params)
    // if (currentPage.value === 1) {
    //   goodsList.value = res.list
    // } else {
    //   goodsList.value = [...goodsList.value, ...res.list]
    // }
    // hasMore.value = res.hasMore
    
    // 模拟数据
    setTimeout(() => {
      const mockData = [
        {
          id: 1,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/223778/18/6959/103158/61cc7965E6f1e0dda/a4a0450759d5614e.jpg',
          name: 'iPhone 13 Pro',
          price: '5999',
          vipPrice: '5899',
          isFreeShipping: true,
          hasDiscount: true
        },
        {
          id: 2,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/106234/8/35183/153829/63f5c4b3Fca3f0094/1f0b2a3d37496aec.jpg',
          name: '华为 Mate 50 Pro',
          price: '6299',
          vipPrice: '6199',
          isFreeShipping: true,
          hasDiscount: false
        },
        {
          id: 3,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/177161/35/30849/53503/63f5c4b3F3d9c3d5d/8db7e7e2c3d1b6c0.jpg',
          name: '小米 13 Pro',
          price: '4999',
          vipPrice: '4899',
          isFreeShipping: true,
          hasDiscount: true
        },
        {
          id: 4,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/140200/32/33451/55488/63f5c4b3F1b7a9b9a/5e9b8b9b9b9b9b9b.jpg',
          name: 'OPPO Find X6 Pro',
          price: '5999',
          vipPrice: '5899',
          isFreeShipping: false,
          hasDiscount: true
        }
      ]
      
      if (currentPage.value === 1) {
        goodsList.value = mockData
      } else if (currentPage.value === 2) {
        goodsList.value = [...goodsList.value, ...mockData]
      } else {
        hasMore.value = false
      }
      
      loading.value = false
    }, 500)
  } catch (error) {
    Taro.showToast({
      title: '获取商品列表失败',
      icon: 'none'
    })
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value) return
  
  currentPage.value++
  getGoodsList()
}

// 点击商品
const onGoodsClick = (goods) => {
  Taro.navigateTo({
    url: `/pages/goods-details/index?id=${goods.id}`
  })
}

// 组件挂载时初始化
onMounted(() => {
  getGoodsList()
})
</script>

<style lang="scss" scoped>
.category-detail {
  .filter-bar {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 44px;
    background-color: #fff;
    border-bottom: 1px solid #eee;
    position: sticky;
    top: 0;
    z-index: 10;
    
    .filter-item {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      font-size: 14px;
      color: #333;
      position: relative;
      
      &.active {
        color: #fa2c19;
      }
      
      &.price-sort {
        .sort-icon {
          display: flex;
          flex-direction: column;
          margin-left: 4px;
        }
      }
    }
  }
  
  .filter-panel {
    display: flex;
    flex-direction: column;
    height: 100%;
    
    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      border-bottom: 1px solid #eee;
      
      .title {
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .panel-content {
      flex: 1;
      padding: 15px;
      overflow-y: auto;
      
      .filter-section {
        margin-bottom: 20px;
        
        .section-title {
          font-size: 14px;
          font-weight: 500;
          margin-bottom: 10px;
        }
        
        .price-range {
          display: flex;
          align-items: center;
          
          .separator {
            margin: 0 10px;
          }
        }
        
        .brand-list,
        .other-filters {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
        }
      }
    }
    
    .panel-footer {
      display: flex;
      justify-content: space-between;
      padding: 15px;
      border-top: 1px solid #eee;
      
      .nut-button {
        flex: 1;
        margin: 0 5px;
      }
    }
  }
  
  .goods-list {
    padding: 10px;
    
    .goods-card {
      display: flex;
      flex-direction: column;
      padding: 8px;
      
      .goods-info {
        padding: 8px 0;
        
        .goods-name {
          font-size: 14px;
          margin-bottom: 5px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .price-info {
          display: flex;
          align-items: center;
          gap: 5px;
          margin-bottom: 5px;
          
          .vip-price {
            color: #ff9500;
            text-decoration: line-through;
          }
        }
        
        .goods-tags {
          display: flex;
          gap: 5px;
        }
      }
    }
    
    .load-more {
      text-align: center;
      color: #999;
      padding: 10px 0;
      font-size: 14px;
      
      .loading {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 5px;
      }
    }
  }
}
</style>